package com.truthbean.jeetb.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by TruthBean on 2016-10-09 15:36.
 */
public class ImageUtils {
    private static final Font MFONT = new Font("Arial Black", Font.PLAIN, 21);

    private static Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    //图片处理
    public static BufferedImage drawImage(HttpServletRequest request, String status) {
        String text = request.getParameter("text");
        if (text == null) {
            text = "null";
        } else {
            try {
                text = new String(text.getBytes("ISO8859-1"), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String imgUrl = request.getParameter("imgUrl");
        if (imgUrl == null) {
            imgUrl = "http://images.csdn.net/20160831/c1_meitu_1.jpg";
        }
        switch (status) {
            case "status-1":
                return drawImg(request, 1);

            case "status-2":
                return drawImg(request, 2);

            case "status-3":
                return drawImg(request, 3);

            case "status-4":
                return drawImg(request, 4);

            case "action-0":
                return getMatrixImg(text);

            case "action-1":
                return dealImgWithWords(getBufImg(imgUrl), text);

            case "action-2":
                return dealImgWithWords(dealImgWithImg(getBufImg(imgUrl), getMatrixImg(text)), text);

            case "status-0":
            default:
                return drawImg(request, 0);
        }
    }

    //图片验证码
    public static BufferedImage drawImg(HttpServletRequest request, int status) {
        int width = 92, height = 32;
        //绘制底图
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        SecureRandom random = new SecureRandom();
        g.setColor(getRandColor(200, 250));
        g.fillRect(1, 1, width - 1, height - 1);
        g.setColor(new Color(102, 102, 102));
        g.drawRect(0, 0, width - 1, height - 1);
        g.setFont(MFONT);
        g.setColor(getRandColor(150, 200));
        //绘制随机线条
        for (int i = 0; i < 155; i++) {
            int x = random.nextInt(width - 1);
            int y = random.nextInt(height - 1);
            int xl = random.nextInt(6) + 1;
            int yl = random.nextInt(12) + 1;
            g.drawLine(x, y, x + xl, y + yl);
        }

        //添加随机数，并添加上随机颜色
        String sRand = "";
        String tmp = null;
        switch (status) {
            case 1:
                for (int i = 0; i < 6; i++) {
                    tmp = StringUtils.getRandomChar();
                    sRand += tmp;
                    g.setColor(new Color(20 + random.nextInt(120), 20 + random
                            .nextInt(120), 20 + random.nextInt(120)));
                    g.drawString(tmp, 14 * i + random.nextInt(8), random.nextInt(12) + 18);
                }
                break;
            case 2:
                for (int i = 0; i < 4; i++) {
                    tmp = StringUtils.getRandJianHan();
                    sRand += tmp;
                    g.setFont(new Font("宋体", Font.BOLD, 20));
                    g.rotate(-0.01);
                    g.setColor(new Color(20 + random.nextInt(120), 20 + random
                            .nextInt(120), 20 + random.nextInt(120)));
                    g.drawString(tmp, 20 * i + random.nextInt(8), random.nextInt(12) + 20);
                }
                break;
            case 3:
                int _add_1 = random.nextInt(100), _add_2 = (int) (Math.pow(-1, random.nextInt())) * random.nextInt(100);
                sRand = String.valueOf(_add_1 + _add_2);
                g.setColor(new Color(20 + random.nextInt(120), 20 + random
                        .nextInt(120), 20 + random.nextInt(120)));
                g.drawString(String.valueOf(_add_1), random.nextInt(8), random.nextInt(12) + 20);
                g.setColor(new Color(20 + random.nextInt(120), 20 + random
                        .nextInt(120), 20 + random.nextInt(120)));
                g.drawString(_add_2 > 0 ? "+" : "-", 28 + random.nextInt(8), random.nextInt(12) + 20);
                g.setColor(new Color(20 + random.nextInt(120), 20 + random
                        .nextInt(120), 20 + random.nextInt(120)));
                g.drawString(String.valueOf(Math.abs(_add_2)), 40 + random.nextInt(8), random.nextInt(12) + 20);
                g.setColor(new Color(20 + random.nextInt(120), 20 + random
                        .nextInt(120), 20 + random.nextInt(120)));
                g.drawString("=", 60 + random.nextInt(8), random.nextInt(12) + 20);
                g.setColor(new Color(20 + random.nextInt(120), 20 + random
                        .nextInt(120), 20 + random.nextInt(120)));
                g.drawString("?", 72 + random.nextInt(8), random.nextInt(12) + 20);
                break;
            case 0:
            default:
                tmp = StringUtils.getRandomCodeChar();
                for (int i = 0; i < 6; i++) {
                    tmp = StringUtils.getRandomCodeChar();
                    sRand += tmp;
                    g.setColor(new Color(20 + random.nextInt(120), 20 + random
                            .nextInt(120), 20 + random.nextInt(120)));
                    g.drawString(tmp, 14 * i + random.nextInt(8), random.nextInt(12) + 18);
                }
                break;
        }
        if (request != null) {
            //将验证码放入session中
            HttpSession session = request.getSession();
            System.out.println(sRand);
            session.setAttribute("rand", sRand);
        }

        g.dispose();
        return image;
    }

    /**
     * 读取图片
     */
    private static BufferedImage getBufImg(String ImgStr) {
        BufferedImage bufImg = null;
        try {
            assert ImgStr != null;
            if (ImgStr.startsWith("http://") || ImgStr.startsWith("https://")) {
                URLConnection urlCon = (new URL(ImgStr)).openConnection();
                InputStream is = urlCon.getInputStream();
                bufImg = ImageIO.read(is);
            } else {
                File file = new File(ImgStr);
                bufImg = ImageIO.read(file);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bufImg;
    }

    /**
     * 在图片上添加文字
     */
    private static BufferedImage dealImgWithWords(BufferedImage image, String words) {
        assert image != null;
        int width = image.getWidth();
        int height = image.getHeight();
        Graphics g = image.getGraphics();
        g.setColor(Color.blue);
        int fontSize = 24;
        g.setFont(new Font("宋体", Font.BOLD, fontSize));
        g.drawString(words, width / 2 - words.length() * fontSize / 2, height / 3);
        return image;
    }

    /**
     * 在图片上添加小图片
     */
    private static BufferedImage dealImgWithImg(BufferedImage bigImg, BufferedImage smallImg) {
        assert bigImg != null;
        Graphics2D g = bigImg.createGraphics();
        int x = (bigImg.getWidth() - smallImg.getWidth()) / 2;
        int y = (bigImg.getHeight() - smallImg.getHeight()) / 2;
        g.drawImage(smallImg, x, y, smallImg.getWidth(), smallImg.getHeight(), null);
        g.dispose();
        return bigImg;
    }

    private static void saveImg(BufferedImage buffImg, String ImgSrc) {
        try (FileOutputStream responseOutputStream = new FileOutputStream(ImgSrc)) {
            ImageIO.write(buffImg, "JPEG", responseOutputStream);
            responseOutputStream.flush();
        } catch (IOException ex) {
            Logger.getLogger(ImageUtils.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    //生成二维码
    public static BufferedImage getMatrixImg(String words) {
        int width = 200;
        int height = 200;
        HashMap hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(words, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException ex) {
            Logger.getLogger(ImageUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }

//    public static void main(String[] args) throws IOException, WriterException {
//        BufferedImage image = getBufImg("https://gss0.bdstatic.com/7051cy89RcgCncy6lo7D0j9wexYrbOWh7c50/zhidaoribao/2016/0830/gm.jpg");
//        BufferedImage small = getBufImg("D:/images/2016051618/3.jpg");
//        saveImg(dealImgWithWords(image, "感冒真的是“无药可医”吗？ "), "D:/images/2016051618/5.jpg");
//        saveImg(dealImgWithImg(image, getMatrixImg("感冒真的是“无药可医”吗？ ")), "D:/images/2016051618/6.jpg");
//        saveImg(getMatrixImg("感冒真的是“无药可医”吗？ "), "D:/images/2016051618/8.png");
//    }
}
